<?php

/**
 * Description of Application_Model_Fix
 *
 * @author Jean Brito
 */
abstract class Application_Model_Fix{

	static public function index($model, $filter = null, $start = null, $limit = null, $sort = null) {
		$data=$model->getData();
		if(count($filter)){
			$data=array();
			foreach($model->getData() as $i=>$row){
				$selecionado=true;
				foreach($filter as $f=>$fil){
					if($row[$fil['property']]!=$fil['value'])$selecionado=false;
				}
				if($selecionado)$data[]=$row;
			}
		}
		$result=array('success'=>true,'message'=>'Registros lidos com sucesso','total'=>count($data),'data'=>$data);
		return $result;
	}

	static public function get($model,$filter) {
		$result=self::index($model,$filter);
		if(isset($result['data'][0]))$result['data']=$result['data'][0];
		return $result;
	}
	static public function autoincrement($field) {
		$data=$field->getModel()->getData();
		$max=0;
		foreach($field->getModel()->getData() as $row){
			$max=$row[$field->getName()]>$max?$row[$field->getName()]:$max;
		}
		return ($max+1);
	}
	static public function post($model,$data) {
		$rows=&$model->getData();
		$row=&$rows[];
		foreach ($model->getFields() as $setup) {
			$field=$setup['name'];
			if(isset($model->{$field})){
				$model->{$field}->setValue($row,isset($data[$field])?$data[$field]:null);
			}
		}
		$model->setData($rows);
		$result=array('success'=>true,'message'=>'Registro incluido com sucesso!','data'=>$row,'total'=>1);
		return $result;
	}

	static public function delete($model,$id) {
		$rows=$model->getData();
		$data=array();$excluido=false;
		foreach ($rows as $row) {
			if($row['id']!=$id){
				$data[]=$row;
			}else{
				$excluido=true;
			}
		}
		if($excluido){
			$model->setData($data);
			return array('success'=>true,'message'=>'Registro excluido com sucesso!','data'=>array(),'total'=>0);
		}
		return array('success'=>false,'message'=>'Registro não encontrado!','data'=>Array(),'total'=>0);
	}

	static public function put($model,$id,$data) {
		$rows=$model->getData();
		foreach ($rows as &$row) {
			if($row['id']==$id){
				foreach ($model->getFields() as $setup) {
					$field=$setup['name'];
					if(isset($model->{$field})){
						$model->{$field}->setValue($row,isset($data[$field])?$data[$field]:null);
					}
				}
				$model->setData($rows);
				return array('success'=>true,'message'=>'Registro atualizado com sucesso!','data'=>$row,'total'=>1);
			}
		}
		$model->setData($rows);
		return array('success'=>false,'message'=>'Registro não encontrado!','data'=>Array(),'total'=>0);
	}

}
